//
//  OAuthViewController.swift
//  FWSinaWeibo
//
//  Created by 范伟 on 16/2/24.
//  Copyright © 2016年 FanWei. All rights reserved.
//

import UIKit

//@objc protocol OauthViewControllerProxy: NSObjectProtocol {
//    /**
//     登陆成功
//     */
//    optional func oauthViewControllerDidLogin()
//}

class OAuthViewController: UIViewController {
    
//    weak var delegate: OauthViewControllerProxy?
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(
            title: "返回",
            style: .Plain,
            target: self,
            action: "clickCloseButton")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充",
            style: .Plain,
            target: self,
            action: "autoFillForm")
        
        // 在纯代码开发中，所有的 view 都要指定背景颜色
        view.backgroundColor = UIColor.whiteColor()
        let url = NetworkTools.shareTools.oauthUrl
        print(url)
        webView.loadRequest(NSURLRequest(URL: url))
    }
    
    @objc private func autoFillForm() {
        let js = "document.getElementById('userId').value ='13362776088';document.getElementById('passwd').value='fty568';"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    @objc private func clickCloseButton() {
        dismissViewControllerAnimated(true, completion: nil)
    }
}

extension OAuthViewController: UIWebViewDelegate {
//    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        // 1. 如果 URL 不是 回调地址，就继续加载页面
//        print(request.URL?.absoluteString)
//        print("redirectUri" + NetworkTools.shareTools.redirectUri)
//        if let urlString = request.URL?.absoluteString where !urlString.hasPrefix(NetworkTools.shareTools.redirectUri) {
//            return true
//        }
//        // 2. 否则判断回调参数，如果授权成功URL 的`查询字符串`中包含 code 参数
//        if let query = request.URL?.query where query.hasPrefix("code=") {
//            print("查询字符串：" + query)
//            //从查询字符串中截取授权码
//            let code = query.substringFromIndex("code=".endIndex)
//            print("授权码：" + code)
//            //发起网络请求做后续操作
//            
//            return false
//        }
//        print("取消授权")
//        dismissViewControllerAnimated(true, completion: nil)
//        return false
//    }
    // Mark: guard let取代if let优化代码
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 1. 如果 URL 不是 回调地址，就继续加载页面
//        print(request.URL?.absoluteString)
//        print("redirectUri" + NetworkTools.shareTools.redirectUri)
        if let urlString = request.URL?.absoluteString
            where !urlString.hasPrefix(NetworkTools.shareTools.redirectUri) {
                return true
        }
        // 2. 否则判断回调参数，如果授权成功URL 的`查询字符串`中包含 code 参数
        guard let query = request.URL?.query where query.hasPrefix("code=") else {
            print("取消授权")
            dismissViewControllerAnimated(true, completion: nil)
            return false
        }
        print("请求字符串" + query)
        //获取请求码
        let code: String = query.substringFromIndex("code=".endIndex)
//        print("code = \(code)")
        //发起网络请求，做后续操作
        NetworkTools.shareTools.loadAccessToken(code) { result in //result in 相当于 (result) -> () in
            guard let result = result else {
                print("网络不给力！")
                return
            }
            //设置用户账户单例数据
            UserAccount.sharedInstance.updateUserAccount(result)
            
            //调用代理方法，执行登陆成功之后的业务逻辑
//            self.delegate?.oauthViewControllerDidLogin?()
            NSNotificationCenter.defaultCenter().postNotificationName(FWWeiBoLoginSuccessedNotification, object: nil)
            //关闭视图控制器
            self.clickCloseButton()
        }
        return false
    }
}
